/**
 *	人员管理
 *	@auth liangpingzheng
 *	@date 2018-02-27
 */
layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {

    //声明变量
    var layer = parent.layer === undefined ? layui.layer : top.layer
            , table = layui.table
            , form = layui.form
            , layedit = layui.layedit
            , laydate = layui.laydate
            , laytpl = layui.laytpl
            , $ = layui.$;

    /**
     * 单选模板封装
     */
    var switchTpl = function (field, text) {
        var strHtml = '{{#  if(d.' + field + ' == "1" || d.' + field + ' == true){ }}'
                + '<input type="checkbox" name="' + field + '" value="{{d.' + field + '}}" lay-skin="switch" lay-text="' + text + '" lay-filter="switch" checked>'
                + '{{#  } else { }}'
                + '<input type="checkbox" name="' + field + '" value="{{d.' + field + '}}" lay-skin="switch" lay-text="' + text + '" lay-filter="switch">'
                + '{{#  } }}';

        return '<div>' + strHtml + '</div>';
    }

    //调用API接口渲染TABLE(方法级)
    var tableIns = table.render({
        elem: "#tableList"
        , url: "/manager/admin"
        , method: 'post'
        , cellMinWidth: 100
//		,page : true
        , page: {
            layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                    // 限定条数   总数、计数  上一页     页     下一页    到第几页、跳
            , curr: 1
            , groups: 10 //显示 连续页码
            , first: '首页'
            , last: '尾页'
        }
        , height: "full-125"
        , limit: 20
        , limits: [20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200]
        , even: true //开启隔行背景
        , cols: [[
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', width: 80, title: 'ID', align: 'center', sort: true, fixed: 'left'}
                //,{ field:'avatar_url', width:60, title: '头像', align:'center', templet:function(d){
                //return '<a href="'+d.avatar_url+'" target="_blank"><img src="'+d.avatar_url+'" height="26" /></a>';
                //}}
                , {field: 'username', width: 120, title: '工号', align: 'center'}
                , {field: 'realname', width: 120, title: '真实姓名', align: 'center', }
//                , {field: 'city_id', width: 120, title: '城市', align: 'center'}
                , {field: 'role_ids', width: 180, title: '角色', align: 'center', }
                //,{ field:'position_name', width:120, title: '职位', align:'center', sort: true }
                //,{ field:'mobile', width:120, title: '手机号码', align:'center', sort: true }
                //,{ field:'email', width:180, title: '邮箱', align:'center', }
//		  ,{ field:'is_admin', width:100, title: '管理员', align:'center', sort: true, templet: '#adminTpl' }
//		  ,{ field:'is_admin', width:100, title: '管理员', align:'center', sort: true, templet: switchTpl('is_admin','是|否') }
                , {field: 'is_admin', width: 100, title: '管理员', align: 'center', sort: true, templet: function (d) {
                        var str = "";
                        if (d.is_admin == 1) {
                            str = '<span class="layui-btn layui-btn-normal layui-btn-xs">是</span>';
                        } else {
                            str = '<span class="layui-btn layui-btn-normal layui-btn-xs layui-btn-danger">否</span>';
                        }
                        return str;
                    }}
                , {field: 'status', width: 100, title: '状态', align: 'center', templet: '#statusTpl', sort: true, templet: function (d) {
                        var str = "";
                        if (d.status == 1) {
                            str = '<span class="layui-btn layui-btn-normal layui-btn-xs">正常</span>';
                        } else {
                            str = '<span class="layui-btn layui-btn-normal layui-btn-xs layui-btn-danger">禁用</span>';
                        }
                        return str;
                    }}
                , {field: 'login_num', width: 104, title: '登录次数', align: 'center'}
                , {field: 'login_time', width: 150, title: '登录时间', align: 'center'}
                , {fixed: 'right', width: 430, title: '功能操作区', align: 'center', toolbar: '#toolBar'}
            ]]
    });

//	//监听状态开关操作
//	form.on('switch(switch)', function(obj){
//		layer.tips(this.value + ' ' + this.name + '：'+ obj.elem.checked, obj.othis);
//	});

    //监听工具条
    table.on('tool(tableList)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
                , layEvent = obj.event //获得 lay-event 对应的值
                , tr = obj.tr; /*获得当前行 tr 的DOM对象*/
        if (layEvent === 'auth') {
            layer.msg('权限设置');
            //角色权限设置
            location.href = "/manager/adminauth/index?type=2&type_id=" + data.id;
        } else if (layEvent === 'role') {
            layer.msg("角色设置");
            var index = layui.layer.open({
                title: "角色配置",
                type: 2,
                content: "/manager/admin/setrole?admin_id=" + data.id,
                area: ["600px", "350px"],
                success: function (layero, index) {
                    //TODO...
                    setTimeout(function () {
                        layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            });

        } else if (layEvent === 'del') {
            layer.confirm('您确定要删除吗？删除后将无法恢复！', function (index) {
//				obj.del(); //删除对应行（tr）的DOM结构
//				layer.close(index);
//				//向服务端发送删除指令

                $.ajax({
                    url: "/" + APP + "/drop",
                    dataType: "json",
                    type: "POST",
                    data: {"id": data.id},
                    beforeSend: function () {
                        layer.msg('正在删除。。。', {
                            icon: 16
                            , shade: 0.01
                            , time: 0
                        });
                    },
                    success: function (res) {
                        if (res.success) {
                            //2秒后关闭
                            layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                                tableIns.reload();
                            });
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    }
                });

            });
        } else if (layEvent === 'edit') {
            layer.msg('编辑操作');
            edit(data.id, data);
        } else if (layEvent === 'reset') {
            layer.msg('初始化密码操作');

            var index = layui.layer.open({
                title: "重置密码",
                type: 2,
                content: "?app=" + APP + "&act=resetPwd&admin_id=" + data.id,
                area: ["450px", "250px"],
                success: function (layero, index) {
                    //TODO...
                    setTimeout(function () {
                        layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            });

        }
    });

    //批量删除
    $(".btnDAll").click(function () {
        var checkStatus = table.checkStatus('tableList'),
                data = checkStatus.data,
                ids = [];
        if (data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            var idsStr = ids.join(",");
            layer.confirm('确定删除选中的数据吗？', {icon: 3, title: '提示信息'}, function (index) {

                $.ajax({
                    url: "/manager/admin/batchdrop",
                    dataType: "json",
                    type: "POST",
                    data: {"id": idsStr, "changeAct": 0},
                    async: false,
                    beforeSend: function () {
                        layer.msg('正在提交。。。', {
                            icon: 16
                            , shade: 0.01
                            , time: 0
                        });
                        $('#submitForm').attr('disabled', "true");
                    },
                    success: function (res) {
                        $('#submitForm').removeAttr("disabled");
                        layer.closeAll();
                        if (res.success) {
                            //2秒后关闭
                            layer.msg(res.msg, {icon: 1, time: 1000}, function () {
                                tableIns.reload();
                            });
                        } else {
                            layer.msg(res.msg, {icon: 5});
                        }
                    },
                    error: function (request) {
                        layer.msg("网络超时", {icon: 5});
                    },
                });

            })
        } else {
            layer.msg("请选择需要删除的数据");
        }
    });

    //搜索功能
    $(".search_btn").on("click", function () {
        if ($(".searchVal").val() != '') {
            table.reload("tableList", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    keyword: $(".searchVal").val()  //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容");
        }
    });

    //添加
    $(".btnAdd").click(function () {
        edit(0);
    });

    //添加或编辑
    function edit(id, data) {
        var title = '新增人员';
        if (id > 0) {
            title = '修改人员';
        }
        var index = layui.layer.open({
            title: title,
            type: 2,
            area: ["685px", "520px"],
            content: "/manager/admin/edit?id=" + id,
            success: function (layero, index) {
                //TODO...
                setTimeout(function () {
                    layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        //layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        });
    }
    ;

    //自定义验证规则
    form.verify({
        realname: function (value) {
            if (value.length < 2) {
                return '真实姓名不得少于2个汉字';
            }
        }
        , note: function (value) {
            layedit.sync(editIndex);
        }
    });

    //监听提交
    form.on('submit(submitForm)', function (data) {
//		layer.alert(JSON.stringify(data.field), {
//			title: '最终的提交信息'
//		});

        var index = layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.2});
        $.post(aUrl, data.field, function (data) {
            if (data.success) {
                layer.close(index);
                layer.msg("保存成功！");
                layer.closeAll("iframe");

                //刷新父页面
                parent.location.reload();

                return false;
            } else {
                layer.close(index);
                layer.msg(data.msg);
            }
        }, 'json');

        return false;
    });

});